package generator.model;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RSSHeadlineGenerator {
	
	private List<String> newsItems;
	
	public RSSHeadlineGenerator(String[] feeds) throws MalformedURLException {
		
		newsItems = new ArrayList<String>();
		
		try {
			SyndFeedInput input = new SyndFeedInput();
			
			//for every feed
			for(String feedUrl : feeds) {
				SyndFeed feed = input.build(new XmlReader(new URL(feedUrl))); //reading XML syndicate
				//String title = feed.getTitle(); 
				
				//Iterate through feed items
				Iterator<?> entryIter = feed.getEntries().iterator(); //iterate over entries
				while ((entryIter).hasNext()) {
					SyndEntry entry = (SyndEntry) entryIter.next();
					String nyhet = entry.getTitle().trim();
					
					nyhet.replace("\"\"\"", "\"");
					
					newsItems.add(nyhet);
				}
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("ERROR: " + ex.getMessage());
		}
		
	}
	
	public String getHeadline() {
		
		//randomize
		Random r = new Random();
		
		return newsItems.get(r.nextInt(newsItems.size()));
	}
	
	public void printAll() {

		int count = 0;
		
		//for every feed
		for(String nyhet : this.newsItems) {


				System.out.println(nyhet);
		
		}
		System.out.println("antal: "+count);
			
	}

}
